/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.mybatis.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.iwindplus.boot.mybatis.domain.property.MybatisProperty.FieldConfig.CryptoConfig;
import com.iwindplus.boot.mybatis.manager.MybatisFieldManager;
import jakarta.annotation.Resource;
import java.sql.PreparedStatement;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

/**
 * MyBatis 入参拦截器（加密/脱敏）
 *
 * @author zengdegui
 * @since 2025/04/22 00:46
 */
@Slf4j
@Intercepts(
    @Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class)
)
public class MybatisInputInterceptor implements Interceptor {

    @Resource
    private MybatisFieldManager mybatisFieldManager;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        final CryptoConfig crypto = this.mybatisFieldManager.getMybatisProperty().getField().getCrypto();
        if (!crypto.getEnabled()) {
            return invocation.proceed();
        }
        if (!crypto.getInputEncrypt() && !crypto.getInputSensitive()) {
            return invocation.proceed();
        }

        ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
        Object parameterObject = parameterHandler.getParameterObject();
        if (ObjectUtil.isNotNull(parameterObject) && !(parameterObject instanceof String)) {
            this.mybatisFieldManager.processHandler(parameterObject, crypto.getInputEncrypt(), crypto.getInputSensitive(), false);
        }
        return invocation.proceed();
    }
}
